#!/bin/bash

# 检查是否提供了redis集群数 
if [ $# -lt 2 ]; then
  echo "请提供生成redis的数目 $0 <redis集群数> <起始端口>"
  exit 1
fi

# 读取参数
num_dirs=$1
starting_port=$2

# 目录前缀
base_dir="./compose/volumes/redis/redis-"

# 模板文件路径
template_conf="./compose/images/redis/redis-cluster.template.conf"
template_file="./compose/images/redis/redis.template.conf"

# 检查模板文件是否存在
if [ ! -f "$template_conf" ] || [ ! -f "$template_file" ]; then
  echo "redis集群文件不存在"
  exit 1
fi

# 获取当前的局域网IP
current_ip=$(hostname -I | awk '{print $1}')

for i in $(seq 1 $num_dirs); do
  redis_dir="${base_dir}${i}"
  mkdir -p "${redis_dir}/data"
  
  # 目标文件夹
  target_dir="./compose/volumes/redis/redis-${i}"
  mkdir -p "$target_dir"
  
  # 复制模板文件
  config_file="${target_dir}/redis-cluster.conf"
  cp "$template_conf" "$config_file"
  cp "$template_file" "${target_dir}/redis.conf"
  
  # 设置自定义端口和IP
  custom_port=$((starting_port + i - 1))
  
  # 替换端口和IP
  sed -i "s/{{cluster_announce_port}}/${custom_port}/g" "$config_file"
  sed -i "s/{{current_ip}}/${current_ip}/g" "$config_file"
done

echo "创建redis集群: $num_dirs集群"
